<template>
  <div class="app-content">
    <panel v-if="match" :sites="autoParseSites" />

    <auto-fill />
  </div>
</template>

<script>
import axios from 'axios'
import Panel from './panel'
import AutoFill from './auto-fill'
import { autoParseSites } from './config/auto-parse-site'
import { remoteConfigUrl } from '@/content/config'


export default {
  name: 'ContentApp',
  components: {
    Panel,
    AutoFill,
  },
  data() {
    return {
      match: false,
      autoParseSites,
    }
  },
  methods: {
    fetchRemoteConfig(){
      let self = this
      axios({
        url: remoteConfigUrl + '?t=' +new Date().getTime(),
        responseType: 'json',
        credentials: "include",
        mode: "no-cors",
        headers: {
          "Accept": "application/json; odata=verbose"
        }
      }).then(res => {
        if(res && res.data){
          if(process?.env?.NODE_ENV === 'development') return
          console.log('====RESUME HELPER SET REMOTE PARSE CONFIG====')
          self.autoParseSites = res.data
        }
      }).finally(() => {
        self.initalEvent()
      })
    },

    initalEvent(){
      console.log('====RESUME HELPER INIT EVENT====')
      let self = this
      const finalSites = this.autoParseSites || autoParseSites
      if(finalSites.some(d => window.location.href.includes(d.path) && window.location.host.includes(d.name))){
        console.log('匹配到目标地址: >>', window.location.href)
        self.match = true
      }

      chrome.runtime.onMessage.addListener(
        // eslint-disable-next-line no-unused-vars
        function(request, sender, sendResponse) {
          // listen for messages sent from background.js
          if (request.message === 'PAGE_URL_CHANGED') {
            if(finalSites.some(d => request.url.includes(d.path) && request.url.includes(d.name))){
              self.match = true
              console.log("matched url: ", request.url)
            }else{
              self.match = false
            }
          }
        })
    }
  },
  mounted() {
    console.log('====RESUME HELPER MOUNTED====')

    this.fetchRemoteConfig()
  },
}
</script>

<style lang="less" scoped>
@import "./styles/app.less";
</style>
